package cn.zucc.edu.bruce.iot;


import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;

public class CustomDialog extends Dialog implements View.OnClickListener {
    private EditText edt_port;
    private SharedPreferences pref;
    private Context mContext;

    public CustomDialog(@NonNull Context context) {
        super(context);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_settings);

        edt_port = findViewById(R.id.edt_port_num);
        pref = mContext.getSharedPreferences("iot", Context.MODE_PRIVATE);
        edt_port.setText(pref.getString("port", ""));
        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        Point size = new Point();
        d.getSize(size);
        p.width = (int) (size.x * 0.7);
        getWindow().setAttributes(p);

        AppCompatButton bt_cancel = findViewById(R.id.bt_cancel);
        AppCompatButton bt_confirm = findViewById(R.id.bt_confirm);

        bt_confirm.setOnClickListener(this);
        bt_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_cancel:
                dismiss();
                break;
            case R.id.bt_confirm:
                String portStr = edt_port.getText().toString();
                try {
                    Integer.parseInt(portStr);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString("port", portStr);
                    editor.apply();
                } catch (NumberFormatException e) {
                    Toast.makeText(mContext, "输入错误", Toast.LENGTH_SHORT).show();
                } finally {
                    dismiss();
                }
                break;
            default:
                break;
        }
    }
}
